package live.zs.securitytokenauthorize.config;

import live.zs.securitytokenauthorize.constant.CacheConstants;
import live.zs.securitytokenauthorize.entity.MyUsersEntity;
import live.zs.securitytokenauthorize.repo.MyUsersRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Objects;

/**
 * @author madison
 * @description
 * @date 2021/7/16 11:39
 */
public class CustomUserDetailsService implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Autowired
    private MyUsersRepository userRepo;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("CustomUserDetailsService loadUserByUsername:{}", username);

        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        MyUsersEntity usersEntity = cache.get(username, MyUsersEntity.class);
        if (Objects.isNull(usersEntity)) {
            usersEntity = userRepo.findByUsername(username)
                    .orElseThrow(() -> new UsernameNotFoundException(username));
            cache.put(username, usersEntity);
        }
        return new CustomUserDetails(usersEntity, AuthorityUtils.createAuthorityList("auth1", "auth2","auth3"));
    }
}
